/*
 * Copyright 2013 Sigurd Randoll <srandoll@digiway.de>.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.digiway.rapidbreeze.server.model.download;

import de.digiway.rapidbreeze.server.model.storage.StorageProvider;
import de.digiway.rapidbreeze.server.model.storage.StorageProviderRepository;
import de.digiway.rapidbreeze.server.model.storage.StorageProviderRepositoryFactory;
import java.io.File;
import java.net.URL;
import java.nio.file.Path;

/**
 *
 * @author Sigurd Randoll <srandoll@digiway.de>
 */
public class DownloadFactory {

    private static StorageProviderRepository storageProviderRepository = StorageProviderRepositoryFactory.getInstance();

    /**
     * Registers a {@linkplain StorageProviderRepository} which will be used to
     * create new {@linkplain Download} instances. If this method is not used,
     * the default repository is used.
     *
     * @param repository
     */
    public static void registerStorageProviderRepository(StorageProviderRepository repository) {
        storageProviderRepository = repository;
    }

    /**
     * Creates a new {@linkplain Download} instance to download from the given
     * {@linkplain URL} to the passed {@linkplain File}.
     *
     * @param url url to download from. Must be registered at the
     * {@linkplain StorageProviderRepository}.
     * @param file if file exists, it will be overwritten
     * @return new instance
     * @throws IllegalArgumentException if there is no storage provider which
     * can handle the given URL.
     */
    public static Download createDownload(URL url, Path file) {
        StorageProvider storageProvider = storageProviderRepository.getStorageProvider(url);
        if (storageProvider == null) {
            throw new IllegalArgumentException("There is not " + StorageProvider.class.getSimpleName() + " available which can handle the URL:" + url);
        }
        Download download = new Download(url, file, storageProvider);
        return download;
    }
}
